﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SampleSite.admin
{
    public partial class getcode : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Response.ContentType = "image/jpeg";
            this.Response.CacheControl = "No-Cache";

            string code = GenerateCode();

            this.Session["loginCode"] = new Tuple<string, DateTime>(code, DateTime.Now);

            this.Response.BinaryWrite(CreateGraphic(code));
        }

        static char[] codes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToArray();

        private static string GenerateCode(int length = 4)
        {
            StringBuilder sb = new StringBuilder();

            Random random = new Random((int)DateTime.Now.Ticks);
            for (int i = 0; i < length; i++)
            {
                sb.Append(codes[random.Next(codes.Length)]);
            }

            return sb.ToString();
        }

        private static byte[] CreateGraphic(string code)
        {
            using (Bitmap bmp = new Bitmap(150, 50))
            using (MemoryStream ms = new MemoryStream())
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.FillRectangle(Brushes.White, 0, 0, 150, 50);

                int offset = 10;
                foreach (var c in code)
                {
                    g.DrawString(
                        c.ToString(),
                        new Font(FontFamily.GenericSansSerif, 36, FontStyle.Bold),
                        Brushes.Black,
                        new PointF(offset, 0));
                    offset += 20;
                }

                bmp.Save(ms, ImageFormat.Jpeg);
                return ms.ToArray();
            }
        }
    }
}